package com.xujie.chat.server.handler;

import com.xujie.chat.message.MessageType;
import com.xujie.chat.message.MsgHeader;
import com.xujie.chat.message.MyMessage;
import com.xujie.chat.server.manager.ClientManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.xujie.chat.message.NettyConstant.CLIENT_ID_KEY;


/**
 * 类说明：消息处理Handler
 *
 * @author Xujie
 * @since 2024/12/28 22:06
 **/
public class MessageHandler extends SimpleChannelInboundHandler<MyMessage> {
	private final Logger log = LoggerFactory.getLogger(MessageHandler.class);

	@Override
	protected void channelRead0(ChannelHandlerContext channelHandlerContext, MyMessage myMessage) throws Exception {
		String byClientId  = channelHandlerContext.channel().attr(CLIENT_ID_KEY).get().toString();

		if (myMessage.getMyHeader().getType() == MessageType.MESSAGE.value()) {
			log.info("收到转发消息: {}", myMessage.getBody());
			// 转发消息
			MsgHeader myHeader = myMessage.getMyHeader();
			String toClientId = myHeader.getToClientId();

			ClientManager.sendMsg(byClientId, toClientId, myMessage.getBody());

		} else if (myMessage.getMyHeader().getType() == MessageType.SHOW_ONLINE_CLIENT.value()) {
			log.info("收到在线客户端列表");
			channelHandlerContext.writeAndFlush(buildMessage(byClientId, ClientManager.getOnlineClients(byClientId)));
		} else {
			channelHandlerContext.fireChannelRead(myMessage);
		}

	}

	private MyMessage buildMessage(String clientId, String body) {
		MyMessage message = new MyMessage();
		MsgHeader msgHeader = new MsgHeader();
		msgHeader.setType(MessageType.MESSAGE.value());
		msgHeader.setClientId(clientId);
		message.setMyHeader(msgHeader);
		message.setBody(body);
		return message;
	}


	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		log.debug("客户端连接成功");
		super.channelActive(ctx);
	}
}
